/**
 * 认证混入
 * 为页面提供认证相关的便捷方法
 */

export default {
  data() {
    return {
      // 认证状态
      authLoading: false,
      authError: null,
      authRetryCount: 0,
      maxAuthRetries: 2
    }
  },

  computed: {
    // 当前用户信息
    currentUser() {
      return this.$auth.getCurrentUser()
    },

    // 当前openId
    currentOpenId() {
      return this.$auth.getCurrentOpenId()
    },

    // 是否已登录
    isLoggedIn() {
      return this.$auth.isLoggedIn()
    },

    // 是否有名片
    hasCard() {
      return this.$auth.hasCard()
    }
  },

  methods: {
    /**
     * 确保用户已登录
     * @param {boolean} showLoading 是否显示加载提示
     * @returns {Promise<boolean>}
     */
    async ensureAuth(showLoading = true) {
      console.log('=== 开始认证流程 ===')
      console.log('页面:', this.$options.name || '未知页面')
      console.log('显示加载提示:', showLoading)
      console.log('重试次数:', this.authRetryCount)

      if (showLoading) {
        this.authLoading = true
        uni.showLoading({ title: '加载中...' })
      }

      try {
        const isLoggedIn = await this.$auth.ensureLogin()
        console.log('认证结果:', isLoggedIn)

        if (!isLoggedIn) {
          this.authRetryCount++
          this.authError = '登录失败，请重试'
          console.log('认证失败，错误信息:', this.authError)
          console.log('重试次数:', this.authRetryCount)
          
          if (this.authRetryCount >= this.maxAuthRetries) {
            console.log('已达到最大重试次数，停止认证')
            this.authError = '认证失败，请检查网络连接'
            return false
          }
          
          return false
        }

        this.authError = null
        this.authRetryCount = 0
        console.log('认证成功')

        // 打印当前用户信息
        const currentUser = this.currentUser
        console.log('当前用户信息:', currentUser)
        console.log('是否已登录:', this.isLoggedIn)
        console.log('是否有名片:', this.hasCard)
        console.log('==================')

        return true
      } catch (error) {
        console.error('认证失败:', error)
        this.authError = error.message || '认证失败'
        return false
      } finally {
        if (showLoading) {
          this.authLoading = false
          uni.hideLoading()
        }
      }
    },

    /**
     * 检查是否需要创建名片
     * @param {string} action 操作名称
     * @returns {boolean}
     */
    checkCardRequired(action = '此操作') {
      if (!this.hasCard) {
        uni.showModal({
          title: '提示',
          content: `请先账户信息才能${action}`,
          showCancel: false,
          confirmText: '去账户信息',
          success: (res) => {
            if (res.confirm) {
              this.goToCreateCard()
            }
          }
        })
        return false
      }
      return true
    },

    /**
     * 跳转到创建名片页面
     */
    goToCreateCard() {
      uni.navigateTo({
        url: '/pagesCard/createCard/createCard'
      })
    },

    /**
     * 跳转到编辑名片页面
     */
    goToEditCard() {
      if (!this.checkCardRequired('编辑名片')) {
        return
      }

      const cardId = this.currentUser?.id
      if (cardId) {
        uni.navigateTo({
          url: `/pagesCard/cardEdit/cardEdit?cardId=${cardId}`
        })
      }
    },

    /**
     * 刷新用户信息
     * @param {boolean} showLoading 是否显示加载提示
     */
    async refreshUserInfo(showLoading = false) {
      if (showLoading) {
        uni.showLoading({ title: '刷新中...' })
      }

      try {
        await this.$auth.queryCurrentUserInfoByOpenId()
        if (showLoading) {
          uni.showToast({
            title: '刷新成功',
            icon: 'success'
          })
        }
      } catch (error) {
        console.error('刷新用户信息失败:', error)
        if (showLoading) {
          uni.showToast({
            title: '刷新失败',
            icon: 'none'
          })
        }
      } finally {
        if (showLoading) {
          uni.hideLoading()
        }
      }
    },

    /**
     * 检查消息状态
     */
    async checkMessageStatus() {
      try {
        const openId = this.$auth.getCurrentOpenId()
        if (!openId) return null

        const app = getApp()
        if (!app || !app.$api) {
          return null
        }

        const res = await app.$api.queryUnreadNotifyNum({
          openId: openId
        })

        if (res.success && res.result) {
          return res.result
        }
        return null
      } catch (error) {
        console.error('检查消息状态失败:', error)
        return null
      }
    },

    /**
     * 获取供应商信息
     */
    async getSupplierInfo() {
      try {
        return await this.$auth.querySupplyDefault()
      } catch (error) {
        console.error('获取供应商信息失败:', error)
        return null
      }
    }
  },

  // 页面生命周期
  async onLoad() {
    // 延迟确保用户已登录，给App更多时间初始化
    setTimeout(async () => {
      if (this.authRetryCount < this.maxAuthRetries) {
        await this.ensureAuth(false)
      }
    }, 2000)
  },

  async onShow() {
    // 页面显示时检查登录状态
    if (!this.isLoggedIn && this.authRetryCount < this.maxAuthRetries) {
      setTimeout(async () => {
        await this.ensureAuth(false)
      }, 2000)
    }
  }
}
